import React, { useState } from 'react';
import { Card, Button, Upload, message, Flex } from 'antd';
import { InboxOutlined } from '@ant-design/icons';
import * as XLSX from 'xlsx';

const { Dragger } = Upload;

const ExcelMerger = () => {
  // 选中的文件列表
  const [selectedFiles, setSelectedFiles] = useState([]);
  // 合并后的数据（目前未实际使用）
  const [mergedData, setMergedData] = useState(null);

  // 处理文件选择事件
  const handleFileChange = (event) => {
    const files = Array.from(event.target.files); // 获取用户选择的文件数组
    setSelectedFiles(prevFiles => [...prevFiles, ...files]); // 保存选中的文件
  };
  

  // 合并多个 Excel 文件的方法
  const mergeExcelFiles = async (files) => {
    let workbook = XLSX.utils.book_new();
    let allData = [];
    let readPromises = files.map(file => {
      return new Promise((resolve) => {
        const reader = new FileReader();
        reader.onload = (e) => {
          const data = e.target.result;
          const workbookData = XLSX.read(data, { type: 'binary' });
          const sheetName = workbookData.SheetNames[0];
          const sheet = workbookData.Sheets[sheetName];
          const jsonData = XLSX.utils.sheet_to_json(sheet);
          resolve(jsonData);
        };
        reader.readAsBinaryString(file);
      });
    });

    // 等待所有文件读取完成
    const results = await Promise.all(readPromises);
    results.forEach(jsonData => allData.push(...jsonData));

    const ws = XLSX.utils.json_to_sheet(allData);
    XLSX.utils.book_append_sheet(workbook, ws, 'Merged Data');
    // 用 array 类型，返回 ArrayBuffer
    const wbout = XLSX.write(workbook, { bookType: 'xlsx', type: 'array' });
    saveAsExcelFile(wbout);
  };

  // 保存合并后的 Excel 文件
  const saveAsExcelFile = (data) => {
    const blob = new Blob([data], { type: 'application/octet-stream' });
    const url = URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = url;
    link.download = 'merged_data.xlsx';
    link.click();
    URL.revokeObjectURL(url);
  };

  const handleClick = () => {
    mergeExcelFiles(selectedFiles);
  };

  const props = {
  name: 'file',
  multiple: true,
  accept:".doc,.docx,.xlsx,.xls,.csv,application/vnd.openxmlformats-officedocument.wordprocessingml.document",
  // customRequest: () => {},
  onChange(info) {
    if (info.file.status !== 'uploading') {
      console.log(info.file, info.fileList, '???');
      // handleFileChange(info.fileList)
      setSelectedFiles(info.fileList.map((item) => {
        delete item.status
        delete item.error
        return item.originFileObj
      }))
      return
    }
    if (info.file.status === 'done') {
      message.success(`${info.file.name} file uploaded successfully`);
    } else if (info.file.status === 'error') {
      message.error(`${info.file.name} file upload failed.`);
    }
  }, 
};

  return (
    <Card hoverable styles={{ body: { padding: 20, overflow: 'hidden' } }}>
      {/* 文件选择输入框，目前多选有问题 */}
      <Dragger {...props}>
        <p className="ant-upload-drag-icon">
          <InboxOutlined />
        </p>
        <p className="ant-upload-text">上传</p>
        <p className="ant-upload-hint">
          支持点击或拖拽选择你要上传的文件
        </p>
      </Dragger>
      {/* <input type="file" multiple onChange={handleFileChange} /> */}
      <Flex justify='flex-end'style={{marginTop: 20}} >
        <Button disabled={selectedFiles.length < 2} onClick={handleClick}>合并表格</Button>
      </Flex>
      {/* 合并成功提示（目前 mergedData 未被赋值） */}
      {mergedData && <div>Data Merged Successfully!</div>}
    </Card>
  );
};

export default ExcelMerger;